package jcommon.chap9_templating.freemarker.withxml;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import freemarker.cache.ClassTemplateLoader;
import freemarker.ext.dom.NodeModel;
import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

// 把XML“当对象”传入
public class WithXML {

	public static void main(String[] args) {
		
		StringWriter writer = new StringWriter( );

		// Create a Configuration object for FreeMarker
		Configuration cfg = Configuration.getDefaultConfiguration( );
		cfg.setTemplateLoader(new ClassTemplateLoader(WithXML.class));
		cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
		
		// Create a File Object for our XML data
		InputStream is = WithXML.class.getResourceAsStream("xmlData.xml");
		NodeModel nodeModel;
		try {
			nodeModel = NodeModel.parse(new InputSource(is));
		} catch (SAXException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		} catch (ParserConfigurationException e) {
			throw new RuntimeException(e);
		}

		Map root = new HashMap( );
		root.put("doc", nodeModel); 

		// A template is processed with a Map and output is sent to a Writer.
		Template template;
		try {
			template = cfg.getTemplate("demo2.ftl");
			template.process(root, writer);
		} catch (IOException e) {
			throw new RuntimeException(e);
		} catch (TemplateException e) {
			throw new RuntimeException(e);
		}
		System.out.println("output: \n" + writer.toString( ));
	}
}
